package com.duojuhe.admin.spring.schedule.task;


import com.duojuhe.cache.SmsRepeatSendCache;
import com.duojuhe.common.constant.SystemConstants;
import com.duojuhe.coremodule.sms.pojo.record.SmsRepeatRecordDto;
import com.duojuhe.coremodule.sms.service.HandlerSmsService;
import com.duojuhe.coremodule.sms.service.SmsSendTaskService;
import com.duojuhe.redis.redisson.RedisSonLockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Slf4j
@Component
public class SmsSendTask {
    @Resource
    private SmsRepeatSendCache smsRepeatSendCache;
    @Resource
    public HandlerSmsService handlerSmsService;
    @Resource
    public SmsSendTaskService smsSendTaskService;
    /**
     * 执行短信发送任务
     */
    public void executeSmsSendTask() {
        if (!SystemConstants.SYSTEM_INIT_SUCCESS) {
            return;
        }
        //并发锁
        String lockKey = "executeSmsSendTask";
        //尝试获取锁
        if (!RedisSonLockUtils.fairTryLock(lockKey)){
            log.info("【定时执行短信发送任务】获取锁失败，跳过本次执行，lockKey：{}",lockKey);
            return;
        }
        log.info("【定时执行短信发送任务】获取锁成功，lockKey：{}",lockKey);
        try {
            //执行重复发送逻辑
            this.executeSmsRepeatSend();
            //执行定时发送任务
            smsSendTaskService.executeSmsSendTask();
        }catch (Exception e){
            log.error("【定时执行短信发送任务】出现异常",e);
        }
        log.info("【定时执行短信发送任务】释放锁，lockKey：{}",lockKey);
        RedisSonLockUtils.unlock(lockKey);
    }

    /**
     * 执行短信重复发送逻辑
     */
    private void executeSmsRepeatSend(){
        //队列数量
        Long size = smsRepeatSendCache.getQueueSize();
        if (size == 0) {
            return;
        }
        log.info("【短信重发】队列里面共有：{}",size);
        log.info("【短信重发】开始......");
        for (int i = 0; i < size; i++) {
            SmsRepeatRecordDto repeatRecordDto = smsRepeatSendCache.takeFromHead();
            if (repeatRecordDto == null) {
                break;
            }
            log.info("【短信重发】记录详情：{}",repeatRecordDto);
            //短信发送服务
            handlerSmsService.handlerSendSms(repeatRecordDto);
        }
        log.info("【短信重发】结束......");
    }
}
